package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class TypeHandler1 implements org.apache.ibatis.type.TypeHandler<String[]> {

    ObjectMapper objectMapper = new ObjectMapper();
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, String[] input, JdbcType jdbcType) throws SQLException {
        String inputString = objectMapper.writeValueAsString(input);
        preparedStatement.setString(index , inputString);
    }

    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);

        return transfer(result);
    }

    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);
        return transfer(result);
    }

    @SneakyThrows
    @Override
    public String[] getResult(CallableStatement callableStatement, int index) throws SQLException {

        String result = callableStatement.getString(index);
        return transfer(result);
    }

    private String[] transfer(String result) throws JsonProcessingException {
        if (result == null || "".equals(result)){
            return new String[0];
        }
        String[] strings = objectMapper.readValue(result, String[].class);
        return strings;
    }
}
